package com.hs.hlw.credit.system.business.service.impl;

import com.hs.hlw.credit.system.business.dto.ResponseDto;
import com.hs.hlw.credit.system.business.service.DataSearchService;
import com.hs.hlw.credit.system.common.enumeration.CommonStatus;
import com.hs.hlw.credit.system.common.enumeration.DataBaseType;
import com.hs.hlw.credit.system.common.enumeration.FormStatus;
import com.hs.hlw.credit.system.common.enumeration.SubmissionBatchType;
import com.hs.hlw.credit.system.common.util.JsonUtil;
import com.hs.hlw.credit.system.data.DataUtils;
import com.hs.hlw.credit.system.data.mybatis.Pageable;
import com.hs.hlw.credit.system.data.primary.mapper.DataSourceMapper;
import com.hs.hlw.credit.system.data.primary.mapper.SubmissionBatchMapper;
import com.hs.hlw.credit.system.data.primary.mapper.SubmissionFormFieldMapper;
import com.hs.hlw.credit.system.data.primary.mapper.SubmissionFormMapper;
import com.hs.hlw.credit.system.data.primary.model.*;
import com.hs.hlw.credit.system.data.util.CommonDataUtil;
import com.hs.hlw.credit.system.data.util.DbUtil;
import com.hs.hlw.credit.system.data.util.DbUtil_DM;
import com.hualongdata.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DataSearchService
 * @author zhb
 * @date 2018/11/26
 */
@Service
public class DataSearchServiceImpl implements DataSearchService {
    private @Autowired SubmissionFormMapper submissionFormMapper;
    private @Autowired DataSourceMapper dataSourceMapper;
    private @Autowired SubmissionFormFieldMapper submissionFormFieldMapper;
    private @Autowired SubmissionBatchMapper submissionBatchMapper;

    /**
     * 查询报送数据详情
     * @param formId
     * @param ID
     * @return
     */
    public ResponseDto searchSubmissionDetail(Integer formId, Integer ID) {
        // 获取表单信息
        SubmissionForm form = checkSubmissionForm(formId);

        // 获取数据源信息
        DataSource dataSource = checkDataSource(form.getDataSourceId());

        // 获取表单字段
        SubmissionFormFieldExample example = new SubmissionFormFieldExample();
        SubmissionFormFieldExample.Criteria criteria = example.createCriteria();
        criteria.andFormIdEqualTo(formId);
        List<SubmissionFormField> fieldList = submissionFormFieldMapper.selectByExample(example);
        Map<String, SubmissionFormField> map = new HashMap<>();
        if (fieldList != null && !fieldList.isEmpty()) {
            for (SubmissionFormField field : fieldList) {
                map.put(field.getFieldCode(), field);
            }
        }

        DataBaseType dataBaseType = DataBaseType.getDataBaseTypeByCode(dataSource.getDatabaseType());
        DbUtil dbUtil = CommonDataUtil.getDbUtilInstance(dataSource);

        Pageable pageable = DataUtils.pageable(1, 1, null, null);
        List<SubmissionFormField> whereList = new ArrayList<>();
        SubmissionFormField field = new SubmissionFormField();
        field.setFieldCode("ID");
        field.setFieldValue(ID.toString());
        field.setLogicOperator((short) 1);
        field.setFieldDataType("VARCHAR");
        whereList.add(field);
        fieldList.add(field);
        List<Map<String, Object>> dataList = dbUtil.page(form.getTableName(), fieldList, whereList, pageable);
        if (dataList == null || dataList.isEmpty()) {
            throw new BusinessException("数据不存在");
        }

        return new ResponseDto("查询成功", dataList.get(0));
    }

    /**
     * 通过批次查询报送数据详情
     * @param batchId
     * @return
     */
    public ResponseDto searchSubmissionDetailByBatch(Integer batchId) {
        // 获取批次信息
        SubmissionBatch batch = submissionBatchMapper.selectByPrimaryKey(batchId);
        if (batch == null) {
            throw new BusinessException("批次不存在");
        }
        if (!SubmissionBatchType.TYPE_1.code.equals(batch.getType())) {
            throw new BusinessException("非表单上报批次，不能获取批次数据信息");
        }

        // 获取表单信息
        SubmissionForm form = checkSubmissionForm(batch.getFormId());

        // 获取数据源信息
        DataSource dataSource = checkDataSource(form.getDataSourceId());

        // 获取表单字段
        SubmissionFormFieldExample example = new SubmissionFormFieldExample();
        SubmissionFormFieldExample.Criteria criteria = example.createCriteria();
        criteria.andFormIdEqualTo(batch.getFormId());
        List<SubmissionFormField> filedList = submissionFormFieldMapper.selectByExample(example);
        Map<String, SubmissionFormField> map = new HashMap<>();
        if (filedList != null && !filedList.isEmpty()) {
            for (SubmissionFormField field : filedList) {
                map.put(field.getFieldCode(), field);
            }
        }

        DbUtil dbUtil = CommonDataUtil.getDbUtilInstance(dataSource);

        Pageable pageable = DataUtils.pageable(1, 1, null, null);
        List<SubmissionFormField> whereList = new ArrayList<>();
        SubmissionFormField field = new SubmissionFormField();
        field.setFieldCode("ADD_BATCH_ID");
        field.setFieldValue(batchId.toString());
        field.setLogicOperator((short) 1);
        field.setFieldDataType("VARCHAR");
        whereList.add(field);
        field = new SubmissionFormField();
        field.setFieldCode("ID");
        field.setFieldDataType("VARCHAR");
        filedList.add(field);
        List<Map<String, Object>> dataList = dbUtil.page(form.getTableName(), filedList, whereList, pageable);
        if (dataList == null || dataList.isEmpty()) {
            throw new BusinessException("数据不存在");
        }

        return new ResponseDto("查询成功", dataList.get(0));
    }


    /**
     * 查询报送数据
     * @param formId
     * @param whereList
     * @param pageable
     * @return
     */
    public ResponseDto searchSubmissionData(Integer formId, List<SubmissionFormField> whereList, Pageable pageable) {
        // 获取表单信息
        SubmissionForm form = checkSubmissionForm(formId);

        // 获取数据源信息
        DataSource dataSource = checkDataSource(form.getDataSourceId());

        // 获取表单字段
        SubmissionFormFieldExample example = new SubmissionFormFieldExample();
        SubmissionFormFieldExample.Criteria criteria = example.createCriteria();
        criteria.andFormIdEqualTo(formId);
        List<SubmissionFormField> filedList = submissionFormFieldMapper.selectByExample(example);
        Map<String, SubmissionFormField> map = new HashMap<>();
        if (filedList != null && !filedList.isEmpty()) {
            for (SubmissionFormField field : filedList) {
                map.put(field.getFieldCode(), field);
            }
        }

        // 获取列表显示的字段
        List<SubmissionFormField> displayList = new ArrayList<>();
        if (filedList != null && !filedList.isEmpty()) {
            for (SubmissionFormField field : filedList) {
                if (CommonStatus.STATUS_1.code.equals(field.getListDisplayStatus())) {
                    displayList.add(field);
                }
            }
        }
        SubmissionFormField dto = new SubmissionFormField();
        dto.setFieldCode("ID");
        dto.setFieldDataType("VARCHAR");
        displayList.add(dto);

        // 获取查询条件
        if (whereList != null && !whereList.isEmpty()) {
            for (SubmissionFormField field : whereList) {
                if (map.get(field.getFieldCode()) != null) {
                    field.setFieldDataType(map.get(field.getFieldCode()).getFieldDataType());
                    field.setRuleCfg(map.get(field.getFieldCode()).getRuleCfg());
                }
            }
        }

        DataBaseType dataBaseType = DataBaseType.getDataBaseTypeByCode(dataSource.getDatabaseType());
        DbUtil dbUtil = null;
        switch (dataBaseType) {
            case TYPE_2:
                dbUtil = DbUtil_DM.getInstance(dataSource.getJdbcUrl(), dataSource.getUserName(), dataSource.getPassword());
                break;
            default:
                throw new BusinessException("暂时不支持" + dataBaseType.value + "数据库");
        }

        List<Map<String, Object>> dataList = dbUtil.page(form.getTableName(), displayList, whereList, pageable);

        return new ResponseDto("查询成功", pageable, dataList);
    }

    /**
     * 校验表单
     *
     * @param formId
     */
    private SubmissionForm checkSubmissionForm(Integer formId) {
        SubmissionForm form = submissionFormMapper.selectByPrimaryKey(formId);
        if (form == null) {
            throw new BusinessException("表单不在存");
        }
        if (FormStatus.STATUS_0.code.equals(form.getStatus())) {
            throw new BusinessException("该报送功能正在升级维护，请稍后再试");
        }
        return form;
    }


    /**
     * 校验数据源
     *
     * @param dataSourceId
     */
    private DataSource checkDataSource(Integer dataSourceId) {
        DataSource dataSource = dataSourceMapper.selectByPrimaryKey(dataSourceId);
        if (dataSource == null) {
            throw new BusinessException("关联数据源不存在");
        }
        DataBaseType dataBaseType = DataBaseType.getDataBaseTypeByCode(dataSource.getDatabaseType());
        if (CommonStatus.STATUS_0.code.equals(dataSource.getStatus())) {
            throw new BusinessException("关联数据源无效");
        }
        if (dataBaseType == null) {
            throw new BusinessException("未知的数据源类型");
        }
        if (!DataBaseType.TYPE_2.code.equals(dataSource.getDatabaseType())) {
            throw new BusinessException("暂时不支持" + dataBaseType.value + "数据库");
        }

        return dataSource;
    }
}